package org.swim.session;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;
import org.swim.entity.Ability;
import org.swim.entity.AddAbilityRequest;
import org.swim.entity.User;

@Stateless
@RemoteBinding(jndiBinding="AbilityRequestManagerRemote")
public class AbilityRequestManager implements AbilityRequestManagerRemote {


	/**
	 * Manager degli entity beans. Permette di interagire direttamente col database inserendo e ricercando dati
	 */
	@PersistenceContext(unitName="swim") private EntityManager manager;
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public int createAbilityRequest(int senderID, int abilityID) {
		
		AddAbilityRequest toDefine=new AddAbilityRequest();
		
		User mittente=manager.find(User.class, senderID);
		Ability required=manager.find(Ability.class, abilityID);
		
		toDefine.setMittente(mittente);
		toDefine.setAbilita(required);
		toDefine.setApprovata(false);
		
		manager.persist(toDefine);
		
		return toDefine.getIdRichiesta();
		
		
		
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void approveAbilityRequest(int adminID, int requestID) {
		
		AddAbilityRequest toApprove=new AddAbilityRequest();
		
		toApprove=manager.find(AddAbilityRequest.class, requestID);
		User u=manager.find(User.class, adminID);
		
		toApprove.setApprovatore(u);
		toApprove.setApprovata(true);
	
	
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void deleteAbilityRequest(int requestID) {
		
		AddAbilityRequest ra= new AddAbilityRequest();
		ra = manager.find(AddAbilityRequest.class, requestID);
		if(ra != null)
			manager.remove(ra);	
		
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<AddAbilityRequest> getAllSuspendedAbilityRequest() {
		
		List<AddAbilityRequest> result = new ArrayList<AddAbilityRequest>();
		
		try 
		{
			Query q = manager.createQuery("SELECT OBJECT(ra) FROM AddAbilityRequest AS ra " +
											"WHERE ra.approvata=false");
			
			@SuppressWarnings("unchecked")
			Collection<AddAbilityRequest> coll = (Collection<AddAbilityRequest>) q.getResultList();

			Iterator<AddAbilityRequest> itar = coll.iterator();
			
			while (itar.hasNext())
			{	
				AddAbilityRequest ra = itar.next();
				result.add(ra);
			}
		} 
		catch (EntityNotFoundException exc){} 
		
		return result;		
	}

	@Override
	public void denyAbilityRequest(int adminID, int requestID) {
		
		AddAbilityRequest toDeny=new AddAbilityRequest();
		
		toDeny=manager.find(AddAbilityRequest.class, requestID);
		
		this.deleteAbilityRequest(requestID);
		
	}

}
